package com.twm.tamauth.api

import android.content.Context
import android.os.Debug
import android.util.Log
import com.google.gson.GsonBuilder
import com.twm.tamauth.api.config.MyAuthApiConfig
import com.twm.tamauth.api.config.GsonTypeAdapterFactory
import com.twm.tamauth.api.data.req.MyAuthHireHeartReq
import com.twm.tamauth.api.data.req.MyAuthLoginReq
import com.twm.tamauth.api.data.resp.MyAuthHireHeartResp
import com.twm.tamauth.api.data.resp.MyAuthLoginResp
import com.twm.tamauth.api.excp.MyAuthApiException
import com.twm.tamauth.api.service.MyAuthOpenService
import com.twm.tamauth.engine.MyAuthNetConfig
import com.twm.tamauth.engine.cookie.PersistentCookieJar
import com.twm.tamauth.engine.interceptor.MyAuthHeaderInterceptor
import com.twm.tamauth.engine.interceptor.MyAuthLogRecordInterceptor
import com.twm.tamauth.engine.okhttp.setDebug
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

object MyAuthOpenApi {

    private var userToken: String = ""
    private var _retrofit: Retrofit? = null
    private var host: String = "https://api.playfuncat.cn/"  // 默认正式环境

    private val retrofit: Retrofit
        get() = _retrofit!!

    /**
     * 接口相关 初始化
     * @param context 应用
     * @param isDebug 是否是测试环境
     */
    fun initialize(context: Context? = null, isDebug: Boolean = false) {
        if (isDebug) {
            host = "http://139.199.193.234"
        }

        MyAuthNetConfig.initialize(context) {
            // 超时设置
            connectTimeout(MyAuthApiConfig.DEF_TIMEOUT, TimeUnit.SECONDS)
            readTimeout(MyAuthApiConfig.DEF_TIMEOUT, TimeUnit.SECONDS)
            writeTimeout(MyAuthApiConfig.DEF_TIMEOUT, TimeUnit.SECONDS)

            // LogCat是否输出异常日志, 异常日志可以快速定位网络请求错误
            setDebug(true)

            // AndroidStudio OkHttp Profiler 插件输出网络日志
            addInterceptor(MyAuthLogRecordInterceptor(true))

            // 添加公共请求头
            addInterceptor(
                MyAuthHeaderInterceptor() {
                    createHeaders()
                }
            )

            context?.let {
                // 添加持久化Cookie管理
                cookieJar(PersistentCookieJar(it))
            }
        }
        _retrofit = defRetrofit(host)
    }

    /**
     *  设置公共请求头
     */
    private fun createHeaders(): HashMap<String, String?> {
        return hashMapOf(
            "Authorization" to userToken,
            "deviceType" to "1"
        )
    }

    /**
     *  更新用户token
     */
    fun updateUserToken(userToken: String) {
        if (userToken.isEmpty()) {
            Log.w("OpenApi", "用户token无效")
            return
        }
        Log.d("OpenApi", "更新用户token=$userToken")
        this.userToken = userToken
    }

    /**
     * 租号自动上号
     * hireOrderAutoLogin
     * @param authUrl  授权地址
     * @param id  业务id
     */
    @Throws(MyAuthApiException::class)
    suspend fun hireOrderAutoLogin(
        authUrl: String,
        id: String
    ): MyAuthLoginResp {
        return getOpenService().hireOrderAutoLogin(
            MyAuthLoginReq(authUrl, id)
        ).convert()
    }

    /**
     * 租号上号后心跳
     * hireHeart
     * @param authCode  上号返回的码
     * @param imgs  截图
     * @param type  1-心跳，2-下线
     */
    @Throws(MyAuthApiException::class)
    suspend fun hireHeart(
        authCode: String,
        imgs: String,
        type: Int
    ): MyAuthHireHeartResp {
        return getOpenService().hireHeart(
            MyAuthHireHeartReq(authCode, imgs, type)
        ).convert()
    }

    /**<其他设置，从Wrapper中提取数据>*/
    @Throws(MyAuthApiException::class)
    private inline fun <reified T> MyAuthWrapper<T>.convert(): T {
        if (code == 200) {
            return result
        } else {
            throw MyAuthApiException(code, message)
        }
    }

    /**<获取Service>*/
    private fun getOpenService(): MyAuthOpenService {
        return retrofit.create(MyAuthOpenService::class.java)
    }

    /**<Retrofit>**/
    private fun defRetrofit(host: String): Retrofit {
        return Retrofit.Builder().baseUrl(host).callFactory(MyAuthNetConfig.okHttpClient)
            .addConverterFactory(
                GsonConverterFactory.create(
                    GsonBuilder().registerTypeAdapterFactory(
                        GsonTypeAdapterFactory()
                    ).create()
                )
            ).build()
    }

    private fun String?.def(defV: String): String =
        if (isNullOrEmpty()) defV else this

}